import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../../constant/view_type.dart';

class PluginPage extends StatefulWidget {
  const PluginPage({Key? key}) : super(key: key);

  @override
  State<PluginPage> createState() => _PluginPageState();
}

class _PluginPageState extends State<PluginPage> {
  MethodChannel methodChannel = const MethodChannel("pluginChannel");
  String resultFromAndroid = "";
  Map params = {"type": ViewSubType.pluginView1, "initText": "初始化文字"};

  @override
  void initState() {
    super.initState();
    methodChannel.setMethodCallHandler((MethodCall call) async {
      if (call.method == "plugin") {
        setState(() {
          resultFromAndroid = call.arguments;
        });
        return "Flutter received";
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("测试插件"),
      ),
      body: Column(
        children: [
          SizedBox(
            height: 120,
            child: getPlatformView(),
          ),
          const Padding(
            padding: EdgeInsets.only(top: 10),
          ),
          Text("Flutter接收到的数据：$resultFromAndroid"),
          const Padding(
            padding: EdgeInsets.only(top: 10),
          ),
          ElevatedButton(
            onPressed: () async {
              String result = await methodChannel.invokeMethod(
                "plugin",
                "send from Flutter",
              );
              setState(() {
                resultFromAndroid = result;
              });
            },
            child: const Text("Flutter发送数据"),
          ),
        ],
      ),
    );
  }

  Widget getPlatformView() {
    if (defaultTargetPlatform == TargetPlatform.android) {
      /**
       * creationParams ：传递的参数，插件可以将此参数传递给 AndroidView 的构造函数。
       * creationParamsCodec ：将 creationParams 编码后再发送给平台侧，它应该与传递给构造函数的编解码器匹配。值的范围：
       *  StandardMessageCodec
       *  JSONMessageCodec
       *  StringCodec
       *  BinaryCodec
       */
      return AndroidView(
        viewType: ViewType.pluginView,
        creationParams: params,
        creationParamsCodec: const StandardMessageCodec(),
      );
    } else if (defaultTargetPlatform == TargetPlatform.iOS) {
      return const UiKitView(
        viewType: ViewType.pluginView,
        creationParams: {"type": ViewSubType.pluginView1, "initText": "初始化文字"},
        creationParamsCodec: StandardMessageCodec(),
      );
    }
    return const Text("发生错误");
  }
}
